package com.pfzy.lib.net.cookie;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import okhttp3.Cookie;
import okhttp3.HttpUrl;
import com.pfzy.lib.config.log.MyLog;

/**
 * 持久Cookie存储
 */
public class PersistentCookieStore {
    private static final String COOKIE_PREFS = "Cookies_Prefs";
    private final SharedPreferences cookiePrefs;
    private final Map<String, ConcurrentHashMap<String, Cookie>> cookies = new HashMap<>();

    public PersistentCookieStore(Context context) {
        Cookie decodedCookie;
        this.cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
        Map<String, ?> prefsMap = this.cookiePrefs.getAll();
        for (Map.Entry<String, ?> entry : prefsMap.entrySet()) {
            String[] cookieNames = TextUtils.split((String) entry.getValue(), ",");
            for (String name : cookieNames) {
                String encodedCookie = this.cookiePrefs.getString(name, null);
                if (encodedCookie != null && (decodedCookie = decodeCookie(encodedCookie)) != null) {
                    if (!this.cookies.containsKey(entry.getKey())) {
                        this.cookies.put(entry.getKey(), new ConcurrentHashMap<>());
                    }
                    this.cookies.get(entry.getKey()).put(name, decodedCookie);
                }
            }
        }
    }

    protected String getCookieToken(Cookie cookie) {
        return cookie.name() + "@" + cookie.domain();
    }

    public void add(HttpUrl url, Cookie cookie) {
        if (url != null && cookie != null) {
            String name = getCookieToken(cookie);
            if (!cookie.persistent()) {
                if (!this.cookies.containsKey(url.host())) {
                    this.cookies.put(url.host(), new ConcurrentHashMap<>());
                }
                this.cookies.get(url.host()).put(name, cookie);
            } else if (this.cookies.containsKey(url.host())) {
                this.cookies.get(url.host()).remove(name);
            }
            SharedPreferences.Editor prefsWriter = this.cookiePrefs.edit();
            ConcurrentHashMap<String, Cookie> urlCookies = this.cookies.get(url.host());
            if (urlCookies != null) {
                prefsWriter.putString(url.host(), TextUtils.join(",", urlCookies.keySet()));
            }
            prefsWriter.putString(name, encodeCookie(new SerializableOkHttpCookies(cookie)));
            prefsWriter.apply();
        }
    }

    public List<Cookie> get(HttpUrl url) {
        ArrayList<Cookie> ret = new ArrayList<>();
        if (this.cookies.containsKey(url.host())) {
            ret.addAll(this.cookies.get(url.host()).values());
        }
        return ret;
    }

    public boolean removeAll() {
        SharedPreferences.Editor prefsWriter = this.cookiePrefs.edit();
        prefsWriter.clear();
        prefsWriter.apply();
        this.cookies.clear();
        return true;
    }

    public boolean remove(HttpUrl url, Cookie cookie) {
        String name = getCookieToken(cookie);
        if (!this.cookies.containsKey(url.host()) || !this.cookies.get(url.host()).containsKey(name)) {
            return false;
        }
        this.cookies.get(url.host()).remove(name);
        SharedPreferences.Editor prefsWriter = this.cookiePrefs.edit();
        if (this.cookiePrefs.contains(name)) {
            prefsWriter.remove(name);
        }
        prefsWriter.putString(url.host(), TextUtils.join(",", this.cookies.get(url.host()).keySet()));
        prefsWriter.apply();
        return true;
    }

    public List<Cookie> getCookies() {
        ArrayList<Cookie> ret = new ArrayList<>();
        for (String key : this.cookies.keySet()) {
            ret.addAll(this.cookies.get(key).values());
        }
        return ret;
    }

    protected String encodeCookie(SerializableOkHttpCookies cookie) {
        if (cookie == null) {
            return null;
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(os);
            outputStream.writeObject(cookie);
            return byteArrayToHexString(os.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            _loge("IOException in encodeCookie: "+ e);
            return null;
        }
    }

    protected Cookie decodeCookie(String cookieString) {
        byte[] bytes = hexStringToByteArray(cookieString);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            Cookie cookie = ((SerializableOkHttpCookies) objectInputStream.readObject()).getCookies();
            return cookie;
        } catch (IOException e) {
            _loge("IOException in decodeCookie: "+ e);
            e.printStackTrace();
            return null;
        } catch (ClassNotFoundException e) {
            _loge("ClassNotFoundException in decodeCookie: "+ e);
            e.printStackTrace();
            return null;
        }
    }

    protected String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte element : bytes) {
            int v = element & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase(Locale.US);
    }

    protected byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }

    private void _logd(String msg) {
        MyLog.logd("PersistentCookieStore " + msg);
    }
    private void _loge(String msg) {
        MyLog.loge("PersistentCookieStore " + msg);
    }
}
